<?php
/*
 +----------------------------------------------------------------------
 + Title        : MiniService 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2023/5/14 7:34
 + Last-time    : 2023/5/14 7:34+ chen2
 + Desc         : MiniService
 +----------------------------------------------------------------------
*/


namespace app\common\service;

use app\http\exception\BadRequestHttpException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\HttpClient\AccessTokenAwareClient;
use EasyWeChat\MiniApp\Application;

class MiniService
{
    public static function getConfig()
    {
        return [
            'app_id' => config("app.wechat.appid"),
            'secret' => config("app.wechat.app_secret"),
            'http'   => [
                'throw'   => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                // 'base_uri' => 'https://api.mch.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri
            ],
        ];
    }

    /**
     * @return AccessTokenAwareClient
     * @throws InvalidArgumentException
     */
    public static function getClient()
    {
        $config = self::getConfig();
        $app = new Application($config);
        return $app->getClient();
    }

    public static function getInstance() : Application
    {
        $config = self::getConfig();
        return new Application($config);
    }

    /**
     * 通过 code 获取 session 信息
     *
     * @param  string  $code
     *
     * @throws InvalidArgumentException
     */
    public function session(string $code) : array
    {
        $config = self::getConfig();
        $app = new Application($config);
        $utils = $app->getUtils();
        $result = $utils->codeToSession($code);
        return $result;
    }

    /**
     * @throws InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     */
    public function decode(string $iv, string $encryptedData, string $sessionKey)
    {
        $config = self::getConfig();
        $app = new Application($config);
        $utils = $app->getUtils();
        return $utils->decryptSession($sessionKey, $iv, $encryptedData);
    }

    public function getMobileByCode($code)
    {
        $api = self::getInstance()
                   ->getClient();
        $response = $api->postJson('/wxa/business/getuserphonenumber', [
            "code" => $code
        ]);
        $res = $response->toArray();
        if ($res['errcode'] !== 0) {
            throw new BadRequestHttpException($res['errmsg']);
        }
        return $res['phone_info']['phoneNumber'];
    }

    /**
     * 获取 session 的缓存 key
     *
     * @param  string  $openId
     *
     * @return string
     */
    protected function getSessionKey(string $openId)
    {
        return config('admin.extensions.wechat.session_key', 'mini.session.').$openId;
    }

    /**
     * 解密消息
     *
     * @param  string  $openId
     * @param  string  $iv
     * @param  string  $encryptedData
     */
    public function decrypt(string $openId, string $iv, string $encryptedData) : array
    {
        $app = new Application(self::getConfig());
        $utils = $app->getUtils();
        //        $sessionKey = Cache::get($this->getSessionKey($openId));
        //        return $utils->decryptSession($sessionKey, $iv, $encryptedData);
    }
}